package emailserving.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.mail.internet.MimeMessage;

/**
 * Created by jack on 1/29/16.
 */
public class EmailSenderImpl implements EmailSender {
    private static final Logger logger = LoggerFactory.getLogger(JobService.class);

    private JavaMailSender javaMailSender;

    public EmailSenderImpl(String host, int port, String username, String password) {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(host);
        javaMailSender.setProtocol("smtp");
        javaMailSender.setPort(port);
        javaMailSender.setDefaultEncoding("UTF-8");
        javaMailSender.setUsername(username);
        javaMailSender.setPassword(password);
        this.javaMailSender = javaMailSender;
    }

    @Override
    public void send(MimeMessage... mimeMessages) {
        try {
            javaMailSender.send(mimeMessages);
        } catch (MailException e) {
            logger.error("send email failure", e);
        }
    }

    @Override
    public MimeMessage createMimeMessage() {
        return javaMailSender.createMimeMessage();
    }
}
